use axum::Json;
use serde_json::{Value, json};
use crate::{reqwest, query, code};
use super::access_token_kf;

// 发送消息接口
async fn msg( corpid:&str, secret:&str, param:Value ) -> Result<Json<Value>, Json<Value>>{
    let access_token = access_token_kf::token(corpid, secret).await?;
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token={}",
        access_token
    );
    let rs = reqwest::post(&url,param).await?;
    if query::i64(&rs, "errcode")?.eq(&0) {
        code::ok()
    }else {
        code::err("发送消息失败")
    }
}
// 撤回消息
pub async fn recall(corpid:&str, secret:&str, param:Value) -> Result<Json<Value>, Json<Value>>{
    let access_token = access_token_kf::token(corpid, secret).await?;
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/kf/recall_msg?access_token={}",
        access_token
    );
    let rs = reqwest::post(&url,param).await?;  // { msgid:, open_kfid }
    if query::i64(&rs, "errcode")?.eq(&0) {
        code::ok()
    }else {
        code::err("撤回消息失败")
    }
}
// 发送消息
pub async fn send_msg(corpid:&str, secret:&str, param:Value) -> Result<Json<Value>, Json<Value>>{
    let t = query::str(&param, "type")?;
    let mut rs = json!({
        "touser" : query::str(&param, "user_id")?,           // 指定接收消息的客户 UserID
        "open_kfid": query::str(&param, "kf_id")?,          // 指定发送消息的客服账号 ID
        "msgid": query::str(&param, "msg_id")?,              // 指定消息 ID
        "msgtype" : t,
    });
    let str = &t[..];
    match str {
         // 文件消息
        "text" => {
            rs[t] = json!({
                format!("{t}") : {
                    "content" : query::str(&param, "content")?        // 内容
                }
            })
        },
        // 链接消息
        "link" => {
            rs[t] = json!({
                format!("{t}") : {
                    "title" : query::str(&param, "title")?,     // 标题 128
                    "desc" : query::str(&param, "desc")?,       // 描述 512
                    "url" : query::str(&param, "url")?,         // 点击后跳转的链接
                    "thumb_media_id": query::str(&param, "media_id")?
                }
            })
        },
        // 小程序消息
        "miniprogram" => {
            rs[t] = json!({
                format!("{t}") : {
                    "appid": query::str(&param, "appid")?,
                    "title": query::str(&param, "title")?,
                    "thumb_media_id": query::str(&param, "media_id")?,
                    "pagepath": query::str(&param, "path")?
                }
            })
        },
        // 名片消息
        "business_card" => {
            rs[t] = json!({
                format!("{t}") : {
                    "appid": query::str(&param, "appid")?,
                    "title": query::str(&param, "title")?,
                    "userid": query::str(&param, "user_id")?,   // 	成员 userid。第三方应用填密文userid，即 open_userid
                }
            })
        },
        // 获客链接消息
        "ca_link" => {
            rs[t] = json!({
                format!("{t}") : {
                    "link_url": query::str(&param, "link_url")?,    // 通过获客助手创建的获客链接
                }
            })
        },
        // 菜单消息
        "msgmenu" => {
            rs[t] = json!({
                format!("{t}") : {
                    "head_content": query::str(&param, "head_content")?,    // 起始文本
                    "list": query::vec(&param, "list")?,
                    "tail_content": query::str(&param, "head_content")?     // 结束文本
                }
            })
        },
        _ => {
            rs[t] = json!({
                format!("{t}") : {
                    "media_id" : query::str(&param, "media_id")?
                }
            })
        }
    };
    msg(corpid, secret, rs).await
}
// 发送客服欢迎语
pub async fn welcome(corpid:&str, secret:&str, param:Value) -> Result<Json<Value>, Json<Value>>{
    let access_token = access_token_kf::token(corpid, secret).await?;
    let url = format!(
        "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg_on_event?access_token={}",
        access_token
    );
    let rs = reqwest::post(&url,param).await?;  // { code:, msgid, msgtype }
    if query::i64(&rs, "errcode")?.eq(&0) {
        code::ok()
    }else {
        code::err("撤回消息失败")
    }
}